package com.twq.func.innerctrl

/**
 * Created by tangweiqun on 2017/11/28.
 */
object ExceptionTest {
  def main(args: Array[String]): Unit = {
    //1、scala中抛异常使用throw关键字
    val n = 5
    val half: Int =
      if (n % 2 == 0)
        n / 2
      else
        throw new RuntimeException("n must be even")
    println(half)

    //2、异常的捕获用catch关键字
    import java.io.FileReader
    import java.io.FileNotFoundException
    import java.io.IOException
    try {
      //val f = new FileReader("input.txt") //这个会抛FileNotFoundException
      // Use and close file
      throw new IOException("test")
    } catch {
      case e@(_: FileNotFoundException | _: IOException) => {
        // Handle missing file
        println("All Exception = " + e.getMessage)

      }
      case ex: Exception => {
        // Handle other I/O error
        println("IOException = " + ex.getMessage)
      }
    }

    //3、finally关键字
    val file = new FileReader("input.txt")
    try {
      // Use the file
    } finally {
      file.close() // Be sure to close the file
    }

    //4、捕获到异常后，可以计算并返回一个值
    import java.net.URL
    import java.net.MalformedURLException
    def urlFor(path: String) =
      try {
        new URL(path)
      } catch {
        case e: MalformedURLException =>
          new URL("http://www.scala-lang.org")
      }

    //5、match关键字，和java的switch类似，，但是比switch强大，就是模式匹配
    //side effect副作用
    val firstArg = if (args.length > 0) args(0) else ""
    firstArg match {
      case "salt" => {
        println("pepper")
      }
      case "chips" => println("salsa")
      case "eggs" => println("bacon")
      case _ => println("huh?")
    }

    //这样写更友好一点，匹配中没有任何的side effect
    val friend =
      firstArg match {
        case "salt" => "pepper"
        case "chips" => "salsa"
        case "eggs" => "bacon"
        case _ => "huh?"
      }
    println(friend)

  }
}
